
/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-79-单词搜索
 * @date 2025/5/9 10:47
 */
public class Solution79 {
    private int[][] orders = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                boolean flag = check(board, visited, i, j, 0, word);
                if (flag) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean check(char[][] board, boolean[][] visited, int row, int col, int k, String word) {
        if (board[row][col] != word.charAt(k)) {
            return false;
        }
        if (k == word.length() - 1) {
            return true;
        }
        visited[row][col] = true;
        boolean res = false;
        for (int[] order : orders) {
            int newRow = row + order[0];
            int newCol = col + order[1];
            if (newRow >= 0 && newRow < board.length
                    && newCol >= 0 && newCol < board[0].length
                    && !visited[newRow][newCol]) {
                boolean flag = check(board, visited, newRow, newCol, k + 1, word);
                if (flag) {
                    // 找到了
                    res = true;
                    break;
                }
            }
        }
        visited[row][col] = false;
        return res;
    }

}
